"""
日志相关API路由
"""
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Query
from backend.models.response_models import BaseResponse, LogEntry
from backend.utils.logger import log_manager

router = APIRouter(prefix="/logs", tags=["日志"])

@router.get("/", response_model=BaseResponse[List[LogEntry]])
async def get_logs(
    limit: Optional[int] = Query(default=100, description="返回的日志数量限制"),
    operation: Optional[str] = Query(default=None, description="按操作类型过滤"),
    success: Optional[bool] = Query(default=None, description="按成功状态过滤")
):
    """获取操作日志"""
    try:
        logs = log_manager.get_logs(
            limit=limit,
            operation_filter=operation,
            success_filter=success
        )
        
        return BaseResponse(
            success=True,
            message=f"获取日志成功，共{len(logs)}条记录",
            data=logs
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取日志失败: {str(e)}"
        )

@router.delete("/", response_model=BaseResponse[None])
async def clear_logs():
    """清空所有日志"""
    try:
        log_manager.clear_logs()
        
        return BaseResponse(
            success=True,
            message="日志已清空",
            data=None
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"清空日志失败: {str(e)}"
        )

@router.get("/operations", response_model=BaseResponse[List[str]])
async def get_operation_types():
    """获取所有操作类型"""
    try:
        logs = log_manager.get_logs()
        operation_types = list(set(log.operation for log in logs))
        operation_types.sort()
        
        return BaseResponse(
            success=True,
            message="获取操作类型成功",
            data=operation_types
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取操作类型失败: {str(e)}"
        ) 